<?php
error_reporting(0);
header("Content-type:text/html;charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Allow-Headers: *");//这里“Access-Token”是我要传到后台的内容key
header("Access-Control-Expose-Headers: *");
require_once "../editer-service/cache.php";
if($_SERVER['REQUEST_METHOD']=='OPTIONS'){
    echo return_data(false,"不支持OPTIONS请求","");
    return;
}
function postFile($path,$name,$filePath){
    $curl = curl_init();
    $cfile = curl_file_create(realpath($filePath),'application/octet-stream',$name);
    curl_setopt($curl, CURLOPT_URL, get_host()."/?explorer/upload/fileUpload");
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
    curl_setopt($curl, CURLOPT_COOKIE, "CSRF_TOKEN=".$_COOKIE['CSRF_TOKEN']."; KOD_SESSION_ID=".$_COOKIE['KOD_SESSION_ID']."; ");
    $data = array(
        "name"=>$name,
        "type"=>"application/octet-stream",
        "size"=>"1",
        "path"=>$path,
        "chunkSize"=>"1",
        "CSRF_TOKEN"=>$_COOKIE['CSRF_TOKEN'],
        "API_ROUTE"=>"explorer/upload/fileUpload",
        "file"=>$cfile
    );
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $res = curl_exec($curl);
    curl_error($curl);
    curl_close($curl);
    $res = json_decode($res,true);
    return $res;
}
function ajax($action){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, get_host()."/?".$action);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, 0);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_COOKIE, "CSRF_TOKEN=".$_COOKIE['CSRF_TOKEN']."; KOD_SESSION_ID=".$_COOKIE['KOD_SESSION_ID']."; ");
    $res = curl_exec($curl);
    curl_error($curl);
    curl_close($curl);
    $res = json_decode($res,true);
    return $res;
}
function loginInfo(){
    $res = ajax("user/view/options");
    $info = $res['data']['user']['info'];
    if(!$info){
        return false;
    }
    return array(
        "name"=>$info['nickName'],
        "username"=>$info['name'],
        "url"=>$info['avatar']
    );
}
function is_https()
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
        return true;
    } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    } elseif (!empty($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], "https") === 0) {
        return true;
    }
    return false;
}
function get_host(){
    $tmpUrl = "http://";
    if (is_https()) {
        $tmpUrl = "https://";
    }
    $tmpUrl = $tmpUrl . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
    $tmpUrl = str_replace('\\', '/', $tmpUrl);
    $pathSz = explode("/", $tmpUrl);
    array_splice($pathSz,count($pathSz)-4);
    return implode("/",$pathSz);
}
$fileIo = file_get_contents('php://input');
$param = json_decode($fileIo,true);
if($_GET['type'] == "0"){
    // 获取配置
    $config = cacheGet("config","config");
    if(!$config){
        echo return_data(false,"当前系统未被配置过",null);
        return;
    }
    $config['password'] = "";
    echo return_data(true,"读取成功",$config);
}else if($_GET['type'] == "1"){
    // 设置配置
    if(!$param['password']){
        echo return_data(false,"请输入密码","");
        return;
    }
    $config = cacheGet("config","config");
    if($config){
        if($param['password'] != $config['password']){
            echo return_data(false,"密码错误",null);
            return;
        }
    }
    cacheSet("config","config",$param);
    echo return_data(true,"设置成功",null);
}else if($_GET['type'] == "2"){
    // 保存文件
    $file_url = $param['file_url'];
    $name = $param['name'];
    $parentPath = $param['parentPath'];
    $content = file_get_contents($file_url);
    if(!$content){
        echo return_data(false,"保存失败:文件数据流获取失败",null);
        return;
    }
    $filePath = md5($parentPath+$name);
    file_put_contents($filePath,$content);
    $res = postFile($parentPath,$name,$filePath);
    unlink($filePath);
    echo return_data($res['code']&&$res['info'],$res['data'],null);
}else if($_GET['type'] == "3"){
    // 保存配置 config = {needPass:false,needLogin:false,password:""}
    $path = $param['path'];
    $cache = cacheGet("file_config_",$path);
    $cache['config'] = $param['config'];
    cacheSet("file_config_",$path,$cache);
    echo return_data(true,"保存配置成功",null);
}else if($_GET['type'] == "4"){
    // 验证是否有修改密码权限
    $cache = cacheGet("file_config_",$param['path']);
    $info = loginInfo();
    if($info && $cache['createUser'] == $info['username']){
        echo return_data(true,"权限充足",null);
    }else{
        echo return_data(false,"权限不足",null);
    }
}else if($_GET['type'] == "5"){
    // 获取在线用户
    $cache = cacheGet("file_config_",$param['path']);
    $zw = $param['zw'];
    if(!$cache['persons']){
        $cache['persons'] = array();
    }
    $info = loginInfo();
    if(!$info){
        $info = array(
            "name"=>"游客",
            "url"=>get_host()."/static/images/common/default-avata.png",
        );
    }
    $info['time'] = time();
    $cache['persons'][$zw] = $info;
    $userMap = array();
    $userList = array();
    foreach ($cache['persons'] as $key => $user) {
        if(time() - $user['time']<20){
            array_push($userList,$user);
            $userMap[$key]=$user;
        }
    }
    $cache['persons']=$userMap;
    cacheSet("file_config_",$param['path'],$cache);
    echo return_data(true,"获取成功",$userList);
}else if($_GET['type'] == "6"){
    // 初始化数据
    $info = loginInfo();
    $cache = cacheGet("file_config_",$param['path']);
    if(!$cache){
        $cache = array(
            "createUser"=> $info['username']
        );
    }else{
        $cache['createUser'] = $info['username'];
    }
    cacheSet("file_config_",$param['path'],$cache);
    echo return_data(true,"文件初始化成功",$cache['file_id']);
}else if($_GET['type'] == "7"){
    // 验证是否具备查看/修改权限
    $cache = cacheGet("file_config_",$param['path']);
    $info = loginInfo();
    $res = null;
    if($cache['createUser'] == $info['username']){
        $res = array(
            "needLogin"=>true,
            "checkLogin"=>true,
            "needPass"=>false,
            "checkPass"=>true
        );
    }else{
        $config = $cache['config'];
        $checkLogin = $config['needLogin']&&$info||!$config['needLogin'];
        $checkPass = $config['needPass']&&$config['password']==$param['password']||!$config['needPass'];
        $res = array(
            "needLogin"=>$config['needLogin'],
            "checkLogin"=>$checkLogin,
            "needPass"=>$config['needPass'],
            "checkPass"=>$checkPass
        );
    }
    echo return_data(true,"获取验证成功",$res);
}else if($_GET['type'] == "8"){
    // 缓存id数据
    $info = loginInfo();
    $cache = cacheGet("file_config_",$param['path']);
    if($cache['createUser'] == $info['username']){
        $cache['file_id'] = $param['file_id'];
        cacheSet("file_config_",$param['path'],$cache);
        echo return_data(true,"设置id成功",null);
        return;
    }
    echo return_data(false,"设置id失败",null);
}else if($_GET['type'] == "9"){
    // 短链接
    $cache = cacheGet("file_config_",$param['path']);
    if(!$cache){
        echo return_data(false,"文件不存在",null);
        return;
    }
    if($param['url']){
        $cache['longUrl'] = $param['url'];
        cacheSet("file_config_",$param['path'],$cache);
    }
    echo return_data(true,"成功",$cache['longUrl']);
}else{
    echo return_data(false,"当前地址已过期","");
}


